package com.neusoft.neuiotms.dcom.service.impl;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.neusoft.bizcore.auth.common.bean.UserBean;
import com.neusoft.bizcore.web.constant.ExceptionConstants;
import com.neusoft.bizcore.web.exception.UnitedException;
import com.neusoft.neuiotms.dcom.converter.KnowledgeCommentConverter;
import com.neusoft.neuiotms.dcom.dto.KnowledgeCommentDTO;
import com.neusoft.neuiotms.dcom.model.Knowledge;
import com.neusoft.neuiotms.dcom.model.KnowledgeComment;
import com.neusoft.neuiotms.dcom.repository.KnowledgeCommentRepository;
import com.neusoft.neuiotms.dcom.repository.KnowledgeRepository;
import com.neusoft.neuiotms.dcom.service.KnowledgeCommentService;

import lombok.extern.slf4j.Slf4j;

@Service
@Slf4j
public class KnowledgeCommentServiceImpl implements KnowledgeCommentService {

    @Autowired
    private KnowledgeCommentRepository knowledgeCommentRepository;

    @Autowired
    private KnowledgeCommentConverter knowledgeCommentConverter;

    @Autowired
    private KnowledgeRepository knowledgeRepository;

    @Override
    public KnowledgeCommentDTO create(final KnowledgeCommentDTO dto, final UserBean user, final Long knowledgeId) {
        Knowledge model;
        try {
            model = this.knowledgeRepository.getOne(knowledgeId);
        } catch (final Exception e) {
            KnowledgeCommentServiceImpl.log.error(e.getMessage(), e);
            throw new UnitedException(ExceptionConstants.ENTITY_NOT_FOUND, new Object[] {knowledgeId });
        }
        if (user != null) {
            dto.setUserCode(user.getUsername());
            dto.setUserName(user.getName());
        }
        final KnowledgeComment comment = this.knowledgeCommentConverter.toModel(dto);
        comment.setKnowledge(model);
        this.knowledgeCommentRepository.save(comment);
        return this.knowledgeCommentConverter.toDTO(comment);
    }

    @Override
    public KnowledgeCommentDTO update(final Long id, final KnowledgeCommentDTO dto) {
        KnowledgeComment model;
        try {
            model = this.knowledgeCommentRepository.getOne(id);
        } catch (final Exception e) {
            KnowledgeCommentServiceImpl.log.error(e.getMessage(), e);
            throw new UnitedException(ExceptionConstants.ENTITY_NOT_FOUND, new Object[] {id });
        }
        model = this.knowledgeCommentConverter.toModel(dto);

        this.knowledgeCommentRepository.save(model);

        return this.knowledgeCommentConverter.toDTO(model);
    }

}
